import config from "../config.js"
import util from "./util.js"

/**
 * @params 请求数据的存放 data/请求的数据/methods请求的类型 1.post 2.get
 * @ 配合async await 做同步操作
 */

const sendrequest = (params={}) =>{
	let token = "";
	if(uni.getStorageSync('token')) token = uni.getStorageSync('token');
	
	return new Promise((resolve,reject)=>{
		uni.request({
		    url: config.url  + '/api' + params.url,
			method:params.methods || 'POST',
		    data: params.data,
			dataType:'json',
		    header: {
		        'content-type': 'application/x-www-form-urlencoded;application/json',
				'token':token
		    },
		    success: (res) => {
				if(res.data.code == 401){
					util.taost({
						title:'请登录',
						callback:res=>{
							uni.clearStorage();
							util.redirectTo('/pages/my/my',{},'switchTab')
						}
					})
				} else {
					resolve(res.data)
				}
				
		    },
			fail:(err)=>{
				reject(err.data)
			}
		});
	})
}

/**
 * @params 请求数据的存放 data/请求的数据/methods请求的类型 1.post 2.get
 */
const asyncSendrequest = (params={}) =>{
	let token = "";
	if(uni.getStorageSync('token')) token = uni.getStorageSync('token');
	uni.request({
	    url: config.url + '/api' + params.url, 
		method:params.methods || 'POST',
	    data: params.data,
		dataType:'json',
	    header: {
	        'content-type':'application/x-www-form-urlencoded;application/json',
			'token':token
	    },
	    success: (res) => {
			if(res.data.code == 401){
				uni.clearStorage();
				util.taost({
					title:'请登录',
					callback:res=>{
						util.redirectTo('/pages/my/my',{},'switchTab')
					}
				})
			} else {
				params.success(res.data)
			}
	    },
		fail:(err)=>{
			if(typeof params.success == 'function') params.success(err.data)
		}
	});
}

export default {
	sendrequest,asyncSendrequest,
};